package com.fzn.yygh.user.controller;

import com.fzn.yygh.common.result.Result;
import com.fzn.yygh.user.service.UserInfoService;
import com.fzn.yygh.user.util.IpUtil;
import com.fzn.yygh.vo.user.LoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author fzn
 * @date 2022/5/10
 * @apiNote
 */
@Api(tags = "用户接口")
@RestController
@RequestMapping("/api/user")
@CrossOrigin
public class UserInfoApiController {
    @Autowired
    private UserInfoService userInfoService;

    @ApiOperation(value = "会员登录")
    @PostMapping("login")
    public Result login(@RequestBody LoginVo loginVo, HttpServletRequest request) {
        // 记录登录的ip地址
        loginVo.setIp(IpUtil.getIpAddr(request));
        Map<String, Object> info = userInfoService.login(loginVo);
        return Result.ok(info);
    }

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @ApiOperation(value = "发送验证码")
    @PostMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone) {
        //从redis获取验证码，如果获取获取到，返回ok
        // key 手机号  value 验证码
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)) {
            return Result.ok();
        }
        //如果从redis获取不到，
        // 生成验证码，
        code = "123456";
        //生成验证码放到redis里面，设置有效时间
        redisTemplate.opsForValue().set(phone,code,2, TimeUnit.MINUTES);
        return Result.ok();
    }
}
